<?php

namespace app\api\controller;

use app\common\model\AdModel;
use app\common\model\ArticleModel;
use app\common\model\CarBrandModel;
use app\common\model\CarServiceModel;
use app\common\model\SystemMsgModel;
use app\common\model\UserCarModel;
use app\common\model\UserCollectModel;
use think\Request;
use think\db;

class IndexController extends BaseController
{

    /**
     * 首页接口
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function index(Request $request)
    {
        //通用数据
        $data = [];

        //搜索金额关键字
        $moneyKey = trim(getSystem("search_money"));

        if ($moneyKey != "") {
            $moneyKey = str_replace(array("\n", "\r\n"), ",", $moneyKey);
            $moneyKey = explode(",", $moneyKey);
            $arrs = [];
            foreach ($moneyKey as $item) {

                if ($end = strpos($item, "万以下") || $end = strpos($item, "万以内")) {
                    $arrs[] = [
                        "min" => 0,
                        "max" => substr($item, 0, $end)
                    ];
                }
                if ($end = strpos($item, "万以上")) {
                    $arrs[] = [
                        "min" => substr($item, 0, $end),
                        "max" => 0
                    ];
                }

                if (strpos($item, "-")) {
                    $arr = explode("-", $item);
                    $arrs[] = [
                        "min" => $arr[0],
                        "max" => substr($arr[1], 0, strpos($arr[1], "万")),
                    ];
                }
            }


            $data['moneyKey'] = $arrs;
        } else {
            $data['moneyKey'] = [];
        }


        //首页菜单
        $carBrand = new CarBrandModel();
        $data['menu'] = $carBrand->getALL([
            'status' => CarBrandModel::SHOW_STATUS,
            'hot' => 1
        ], 7);

        //二手车知识百科
        $data['article'] = ArticleModel::getKeyArticle("1", 5, true);

        //小白服务
        $carSvr = new CarServiceModel();
        $data['service'] = $carSvr->getALL(['status' => CarServiceModel::SHOW_STATUS], 2);

        //获取用户数据
        if (empty($request->token)) {
            $data['userBook'] = [];
            $data['userCollect'] = [];
        } else {
            $user_id = $request->user["uid"];
            $data['userBook'] = [];

            $uc = new UserCollectModel();
            $data['userCollect'] = $uc->getALL(["user_id" => $user_id], 3);
        }

        //成功返回数据
        return backSuccess($data);
    }

    /**
     * 获取广告
     * @param Request $request
     * @param pid 广告位置ID
     * @return \think\response\Json
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function getAd(Request $request)
    {
        $pid = $request->pid;
        $list = AdModel::getAdList($pid);
        if (empty($list)) {
            backError("没有相关广告数据", 404);
        }
        return backSuccess($list);
    }

    /**
     * 首页推荐
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function recommend(Request $request)
    {
        $userCar = new UserCarModel();

        $list = $userCar->getUserCar();

        return backSuccess($list);
    }

    /**
     * 获取热门关键字
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function searchKeyWord()
    {
        //搜索金额关键字
        $moneyKey = trim(getSystem("search_hot"));

        if ($moneyKey != "") {
            $moneyKey = str_replace(array("\n", "\r\n"), ",", $moneyKey);
            $data['search_hot'] = explode(",", $moneyKey);
        } else {
            $data['search_hot'] = [];
        }

        return backSuccess($data);
    }

    /**
     * 获取客服信息
     * @return \think\response\Json
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function getServer()
    {
        $data = [
            "svr_head" => getSystem("server_head"),
            "svr_name" => getSystem("server_name"),
            "svr_ewm" => getSystem("server_ewm"),
            "svr_wechat" => getSystem("server_wechat"),
            "server_phone" => getSystem("server_phone"),
        ];

        return backSuccess($data);
    }

    /**
     * 获取用户系统消息
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function getSysMsg(Request $request)
    {
        $sysMsg = new SystemMsgModel();

        $user_id = $request->user["uid"];

        $list = $sysMsg->getALL(["send_user_id" => $user_id]);

        SystemMsgModel::where('send_user_id', 'in', [$user_id, '0'])->update(['read_status' => 1]);

        return backSuccess($list);
    }


    /**
     * 用户上传
     * @param $file
     * @return array
     */
    public function share(Request $request)
    {
        $file = $request->content;

        if (empty($file)) return backError("错误！");

        $uid = str_pad(mt_rand(10, 99999), 5, "0", STR_PAD_BOTH);
        if (!empty($request->user["uid"])) {
            $uid = $request->user["uid"];
        }


        $dir_path = '/uploads/users/';
        $up_dir_url = '.' . $dir_path;

        if (!is_dir($up_dir_url)) {
            mkdir($up_dir_url, 0777, true);
        }

        $dir_path = $dir_path . 'share/';
        $up_dir_url = '.' . $dir_path;
        if (!is_dir($up_dir_url)) {
            mkdir($up_dir_url, 0777, true);
        }

        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $file, $result)) {
            $type = $result[2];

            if (in_array($type, config("img_ext_arr"))) {
                $new_file = $up_dir_url . $uid . '.' . $type;
                $fileUrl = $dir_path . $uid . '.' . $type;

                $info = file_put_contents($new_file, base64_decode(str_replace($result[1], '', $file)));
                if ($info) {
                    return backSuccess($fileUrl);
                } else {
                    return backError("分享失败，请重新操作！");
                }
            } else {
                //文件类型错误
                return backError("分享失败，请重新操作！");
            }
        }
    }

    /**
     * 将图片转换成base64编码
     * @param Request $request
     * @return \think\response\Json
     */
    function toBase64(Request $request)
    {
        if (empty($request->img)) return backError('错误！');

        $image_file = "." . $request->img;

        $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
        $base64_image = 'data:png;base64,' . chunk_split(base64_encode($image_data));
        return backSuccess($base64_image);
    }

    /**
     * 用户上传
     * @return \think\response\Json
     */
    public function userUpload(Request $request)
    {
        // 获取表单上传文件 例如上传了001.
        $file = $request->file('file');
        $dir_path = '/uploads/users/';
        //'.date('Ymd').'/'

        if(!empty($request->content)){
            return $this->userUpload64($request->content);
        }

        $up_dir_url = '.' . $dir_path;

        if (!is_dir($up_dir_url)) {
            mkdir($up_dir_url);
        }

        $dir_path = $dir_path . date('Ymd') . '/';
        $up_dir_url = '.' . $dir_path;
        if (!is_dir($up_dir_url)) {
            mkdir($up_dir_url);
        }

        // 移动到根目录
        $info = $file->validate(['size' => config("img_size"), 'ext' => config("img_ext")])
            ->rule('md5')
            ->move($up_dir_url);

        if ($info) {
            $data = [
                "code" => 1,
                "msg" => "上传成功",
                "data" => [
                    'url' => $dir_path . $info->getSaveName()
                ]
            ];
            return json($data);
        } else {
            // 上传失败获取错误信息
            $data = ["code" => 0, "msg" => "上传失败", "data" => $file->getError()];
            return json($data);
        }
    }

    /**
     * 用户上传
     * @param $file
     * @return array
     */
    private function userUpload64($file, $dir_path = '/uploads/users/')
    {
        set_time_limit(0);

        $up_dir_url = '.' . $dir_path;

        if (!is_dir($up_dir_url)) {
            mkdir($up_dir_url, 0777, true);
        }

        $dir_path = $dir_path . date('Ymd') . '/';
        $up_dir_url = '.' . $dir_path;
        if (!is_dir($up_dir_url)) {
            mkdir($up_dir_url, 0777, true);
        }

        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $file, $result)) {
            $type = $result[2];

            if (in_array($type, config("img_ext_arr"))) {
                $new_file = $up_dir_url . md5($file) . '.' . $type;
                $fileUrl = $dir_path . md5($file) . '.' . $type;

                $info = file_put_contents($new_file, base64_decode(str_replace($result[1], '', $file)));
                if ($info) {
                    $data = [
                        "code" => 1,
                        "msg" => "上传成功",
                        "data" => [
                            'url' => $fileUrl
                        ]
                    ];

                    return json($data);
                } else {
                    return json(["code" => 0, "msg" => "上传失败"]);
                }
            } else {
                //文件类型错误
                return json(["code" => 0, "msg" => "格式错误！"]);
            }
        }
    }

    /**
     * 检测版本
     * @return \think\response\Json
     */
    public function checkV(){
        return backSuccess("1.0");
    }
}
